package zhr.chapter9.dadishu;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;

public class GameJFrame extends JFrame {
    ArrayList<JButton> arrayButtons;
    Random ra;
    int currentIndex = 0;
    int score = 0;
    javax.swing.Timer timer;
    // 获取项目的根目录路径
    String projectPath = System.getProperty("user.dir");
    // 拼接资源文件的完整路径
    String image1Path = projectPath + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator + "zhr" + File.separator + "chapter9" + File.separator + "dadishu" + File.separator + "1.png";
    String image2Path = projectPath + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator + "zhr" + File.separator + "chapter9" + File.separator + "dadishu" + File.separator + "3.gif";

    public GameJFrame() {
        ra = new Random();
        currentIndex = ra.nextInt(9);
        timer = new javax.swing.Timer(800, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                timerStart(e);
            }
        });
        initComponents();
        arrayButtons = new ArrayList<>();
        for (int i = 0; i < 9; i++) {
            JButton button = new JButton(new ImageIcon(image1Path));
            button.setSize(220, 220);
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    buttonClicked(e);
                }
            });
            arrayButtons.add(button);
            this.add(button);
        }

        arrayButtons.get(currentIndex).setIcon(new ImageIcon(image2Path));
        timer.start();
    }

    private void initComponents() {
        this.setLayout(new GridLayout(3,3));
    }


    private void buttonClicked(ActionEvent e) {
        if ((e.getSource()).equals(arrayButtons.get(currentIndex))) {
            score += 10;
            this.setTitle("您的得分:" + String.valueOf(score) + "分");
        }
    }

    private void timerStart(ActionEvent e) {
        arrayButtons.get(currentIndex).setIcon(new ImageIcon(image1Path));
        currentIndex = ra.nextInt(9);
        arrayButtons.get(currentIndex).setIcon(new ImageIcon(image2Path));
    }
}
